import { defineStore } from "pinia";
import { Local } from "@/utils/storage";
import { nextTick } from "vue";

export const useMenusStore = defineStore("permission", {
  state: () => {
    return {
      tabsList: [] as any,
      // tabsList: [{ key: "Home", name: "首页", path: "/" }],
      tabsActive: "/home",
    };
  },
  getters: {},
  actions: {
    // 设置状态
    setTabs(node: any) {
      this.tabsList.push(node);
    },
    // 更新状态
    updateTabs(node: any) {
      this.tabsList = node.tabsList;
      this.tabsActive = node.tabsActive;
    },
    // 删除状态
    delTabs(node: any) {
      /*返回和node不相同的元素，就相当于把相同的元素删掉了*/
      this.tabsList = this.tabsList.filter((item: any) => {
        if (item.key == node) {
          return false;
        } else return true;
      });
    },
    setActive(value: any) {
      this.tabsActive = value;
    },
    tabsLogout() {
      this.tabsList = [];
      this.tabsActive = '/Home';

      // 移除本地保存的数据
      Local.remove('permissions');
    }
  },
});

nextTick(() => {
  const useMenuList = useMenusStore();
  // 监听状态变化，将状态执行化
  useMenuList.$subscribe((mutation: any, state: any) => {
    mutation;
    // 保存到浏览器localStorage中
    Local.set("permissions", state);
  });
});
